package com.smart.nine.spel.expr.safe;

import com.smart.nine.spel.expr.PlaceOfBirth;
import com.smart.nine.spel.expr.User;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * 安全导航操作符
 *
 * @author junrui.wang
 * @create 2019/4/2
 */
public class SafeExprSample {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        User user = new User();
        PlaceOfBirth placeOfBirth = new PlaceOfBirth("中国", "厦门");
        user.setPlaceOfBirth(placeOfBirth);

        EvaluationContext context = new StandardEvaluationContext(user);
        String city = parser.parseExpression("placeOfBirth.city").getValue(context, String.class);
        System.out.println(city);

        User user2 = new User();
        user2.setPlaceOfBirth(null);

        EvaluationContext context2 = new StandardEvaluationContext(user2);
        /*String city2 = parser.parseExpression("placeOfBirth.city").getValue(context2, String.class);
        System.out.println(city2);*/

        //设置安全导航操作符
        String city2 = parser.parseExpression("placeOfBirth?.city").getValue(context2, String.class);
        System.out.println(city2);
    }
}
